package fr.utbm.gi.in56.message;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.utbm.gi.in56.ads.AdServlet;
import fr.utbm.gi.in56.user.UserBean;

/**
 * Servlet implementation class MessageServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet("/MessageServlet")
public class MessageServlet extends AdServlet {
       
    /**
	 * Version number associated to the serializable class.
	 */
	private static final long	serialVersionUID	= -4943952950162794644L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public MessageServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{		
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		
		String box = request.getParameter( "box" ); //$NON-NLS-1$
		
		// Get the current user
		HttpSession session = request.getSession( true );
		UserBean user = (UserBean)session.getAttribute( "currentSessionUser" ); //$NON-NLS-1$
		
		if( box.compareTo( "in" ) == 0 ) //$NON-NLS-1$
		{
			MessageManager msgMg = new MessageManager( getConnection() );
			List< Message > msgList = msgMg.getMessages( user.getLogin(), MessageType.INBOX );
			
			request.setAttribute( "msgList", msgList ); //$NON-NLS-1$
			request.setAttribute( "box", "in" ); //$NON-NLS-1$ //$NON-NLS-2$
			
			msgMg.setMessagesAsRead( user.getLogin() );
			
			RequestDispatcher rd = request.getRequestDispatcher( "showMessages.jsp" ); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
		else if( box.compareTo( "out" ) == 0 ) //$NON-NLS-1$
		{
			MessageManager msgMg = new MessageManager( getConnection() );
			List< Message > msgList = msgMg.getMessages( user.getLogin(), MessageType.SENT);
			
			request.setAttribute( "msgList", msgList ); //$NON-NLS-1$
			request.setAttribute( "box", "out" ); //$NON-NLS-1$ //$NON-NLS-2$
			
			RequestDispatcher rd = request.getRequestDispatcher( "showMessages.jsp" ); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
	}
}
